package com.eg366.nioLearn.baseSocket.chapter02.TCP;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

public class InputStreamTest {
	public static void main(String[] args) throws SocketException, IOException {
		byte[] data = "123".getBytes();
		InputStream in  = new ByteArrayInputStream(data);
		
		int totalBytesRcvd = 0;
		int bytesRcvd;
		while(totalBytesRcvd < data.length) {
			/*
			 * data:读入数据的缓冲区；
			 * totalBytesRcvd:data数组的偏移量；
			 * data.length - totalBytesRcvd:要读取的最大字节数
			 * 返回:读入缓冲区的字节数
			 * 注意:之所以用while循环用多个read来接收返回数据，因为返回数据时的返回数据被TCP协议分割成多个部分进行返回
			 */
			if((bytesRcvd = in.read(data, totalBytesRcvd, data.length - totalBytesRcvd)) == -1) {
				throw new SocketException("Connection closed prematurely");
			}
			totalBytesRcvd += bytesRcvd;
		}
		
		System.out.println("Received:" + new String(data));
	}
}
